import { isNull } from '@src/util/type';
/* util */
import { isFalsy } from '@src/util/type';
import { getRootWindow } from '@src/util/dom'
/* vue */
import { defineComponent } from 'vue'
/* hooks */
import { useFetchSettingGPTRobotAppList, useFetchSettingGPTSystemRobot } from '@gpt/hooks';
/* types */
import { SettingGPTServiceItem } from '@gpt/types';
/* model */
import { SettingGPTServiceTypeEnum } from '@gpt/model';

export default defineComponent({
  name: 'SettingGPTRobotSummaryMixin',
  setup() {
    
    const {
      loading: fetchGptRobotLoading,
      fetchGptSystemRobot,
      gptSystemRobot
    } = useFetchSettingGPTSystemRobot()
    
    const {
      loading: fetchGptRobotAppListLoading,
      fetchGptRobotAppList,
      gptRobotAppList
    } = useFetchSettingGPTRobotAppList()
    
    return {
      fetchGptRobotLoading,
      fetchGptSystemRobot,
      gptSystemRobot,
      fetchGptRobotAppListLoading,
      fetchGptRobotAppList,
      gptRobotAppList
    }
    
  },
  data() {
    return {
      // 是否有AI摘要应用能力
      isHaveAISummaryApp: false
    }
  },
  computed: {
    /** 
     * @description 是否有 AI 的灰度
    */
    isHaveAIGray() {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow?.grayAuth?.chat_GPT)
    },
    /** 
     * @description 是否显示AI摘要
     * 1. 有 AI 的灰度
     * 2. 有 AI 摘要应用
    */
    isShowAISummary(): boolean {
      return this.isHaveAIGray && this.isHaveAISummaryApp
    },
    systemRobotId(): number {
      return this.gptSystemRobot?.id as unknown as number
    }
  },
  methods: {
    /** 
     * @description 检查AI摘要应用
    */
    setTimeoutCheckAISummaryApp() {
      setTimeout(() => {
        this.checkAISummaryApp()
      }, 1000)
    },
    checkAISummaryApp() {
      
      // 如果没有对应的灰度，直接返回
      if (isFalsy(this.isHaveAIGray)) {
        return
      }
      
      this.checkAISummaryAppImpl()
      
    },
    async checkAISummaryAppImpl() {
      
      // 1. 获取系统机器人
      await this.fetchGptSystemRobot()
      
      const isDelete = isNull(this.gptSystemRobot.deleteTag) || Boolean(this.gptSystemRobot.deleteTag)
      const isEnabled = Boolean(this.gptSystemRobot.enable)
      
      if (isDelete || isFalsy(isEnabled)) {
        return
      }
      
      // 2. 获取机器人应用列表
      await this.fetchGptRobotAppListHandler()
      // 3. 判断是否有AI摘要应用
      this.checkIsHaveAISummaryAppHandler()
      
    },
    /** 
     * @description 判断是否有AI摘要应用
    */
    checkIsHaveAISummaryAppHandler() {
      
      const summaryApp = this.gptRobotAppList.find((item: SettingGPTServiceItem) => {
        return item.type == SettingGPTServiceTypeEnum.Summary
      })
      
      this.isHaveAISummaryApp = Boolean(summaryApp)
      
    },
    fetchGptRobotAppListHandler() {
      
      const params = {
        robotId: this.gptSystemRobot.id as unknown as number
      }
      
      return this.fetchGptRobotAppList(params)
    }
  },
  mounted() {
    this.setTimeoutCheckAISummaryApp()
  }
})

